package service

import (
	"context"
	"errors"
	"fmt"
	"order_srv/basic/config"
	__ "order_srv/basic/orderproto"
	"order_srv/handler/models"
	"sync"
	"time"
)

// ComprehensiveValidation 综合验证
func (s *Server) ComprehensiveValidation(ctx context.Context, req *__.ComprehensiveValidationReq) (*__.ComprehensiveValidationResp, error) {
	startTime := time.Now()
	validationID := fmt.Sprintf("VAL_%d", startTime.Unix())

	// 参数验证
	if req.StartDate == "" || req.EndDate == "" {
		return nil, errors.New("开始日期和结束日期不能为空")
	}

	// 查询指定日期范围内的订单
	orders, err := s.getOrdersInRange(req.StartDate, req.EndDate)
	if err != nil {
		return nil, fmt.Errorf("查询订单失败: %v", err)
	}

	// 初始化响应
	resp := &__.ComprehensiveValidationResp{
		ValidationId:  validationID,
		StartTime:     startTime.Format("2006-01-02 15:04:05"),
		TotalOrders:   int32(len(orders)),
		ValidOrders:   0,
		InvalidOrders: 0,
		ErrorCount:    0,
		WarningCount:  0,
		Success:       true,
		Errors:        make([]string, 0),
		Warnings:      make([]string, 0),
		Details:       make([]*__.OrderValidationDetail, 0),
	}

	// 并发验证所有订单
	var wg sync.WaitGroup
	var mu sync.Mutex
	validCount := int32(0)
	invalidCount := int32(0)
	errorCount := int32(0)
	warningCount := int32(0)

	for _, order := range orders {
		wg.Add(1)
		go func(o models.Orders) {
			defer wg.Done()

			detail := s.validateOrder(ctx, o, req)

			mu.Lock()
			if detail.Valid {
				validCount++
			} else {
				invalidCount++
			}
			errorCount += int32(len(detail.Errors))
			warningCount += int32(len(detail.Warnings))
			resp.Details = append(resp.Details, detail)
			mu.Unlock()
		}(order)
	}

	wg.Wait()

	// 更新统计信息
	resp.ValidOrders = validCount
	resp.InvalidOrders = invalidCount
	resp.ErrorCount = errorCount
	resp.WarningCount = warningCount

	// 收集所有错误和警告
	for _, detail := range resp.Details {
		resp.Errors = append(resp.Errors, detail.Errors...)
		resp.Warnings = append(resp.Warnings, detail.Warnings...)
	}

	// 生成汇总
	resp.Summary = s.generateValidationSummary(resp)
	resp.Success = resp.Summary.OverallSuccess

	// 计算错误率和警告率
	if resp.TotalOrders > 0 {
		resp.Summary.ErrorRate = float32(resp.ErrorCount) / float32(resp.TotalOrders) * 100
		resp.Summary.WarningRate = float32(resp.WarningCount) / float32(resp.TotalOrders) * 100
	}

	endTime := time.Now()
	resp.EndTime = endTime.Format("2006-01-02 15:04:05")
	resp.DurationMs = endTime.Sub(startTime).Milliseconds()

	return resp, nil
}

// getOrdersInRange 获取指定日期范围内的订单
func (s *Server) getOrdersInRange(startDate, endDate string) ([]models.Orders, error) {
	var orders []models.Orders
	start, _ := time.Parse("2006-01-02", startDate)
	end, _ := time.Parse("2006-01-02", endDate)

	err := config.DB.Where("create_at >= ? AND create_at < ?", start, end).Find(&orders).Error
	return orders, err
}

// validateOrder 验证单个订单
func (s *Server) validateOrder(ctx context.Context, order models.Orders, req *__.ComprehensiveValidationReq) *__.OrderValidationDetail {
	detail := &__.OrderValidationDetail{
		OrderId:  order.Id,
		OrderSn:  order.OrderSn,
		UserId:   order.UserId,
		Status:   int32(order.OrderStatus),
		Amount:   float32(order.Price),
		PayWay:   int32(order.PayWay),
		PayTime:  order.PayTime.Format("2006-01-02 15:04:05"),
		Valid:    true,
		Errors:   make([]string, 0),
		Warnings: make([]string, 0),
	}

	// 根据请求参数决定验证哪些项目
	if req.ValidateIncome {
		if err := s.validateIncomeRecord(order); err != nil {
			detail.Errors = append(detail.Errors, fmt.Sprintf("收入记录验证失败: %v", err))
			detail.Valid = false
		}
	}

	if req.ValidateExpense {
		if err := s.validateExpenseRecord(order); err != nil {
			detail.Warnings = append(detail.Warnings, fmt.Sprintf("支出记录验证失败: %v", err))
		}
	}

	if req.ValidatePayment {
		if err := s.validatePaymentProcessing(order); err != nil {
			detail.Errors = append(detail.Errors, fmt.Sprintf("支付处理验证失败: %v", err))
			detail.Valid = false
		}
	}

	if req.ValidateRefund && order.OrderStatus == 7 { // 已退款
		if err := s.validateRefundProcessing(order); err != nil {
			detail.Errors = append(detail.Errors, fmt.Sprintf("退款处理验证失败: %v", err))
			detail.Valid = false
		}
	}

	if req.ValidateCalculation {
		if err := s.validateCalculationLogic(order); err != nil {
			detail.Warnings = append(detail.Warnings, fmt.Sprintf("计算逻辑验证失败: %v", err))
		}
	}

	if req.ValidateConsistency {
		if err := s.validateDataConsistency(order); err != nil {
			detail.Errors = append(detail.Errors, fmt.Sprintf("数据一致性验证失败: %v", err))
			detail.Valid = false
		}
	}

	return detail
}

// validateIncomeRecord 验证收入记录
func (s *Server) validateIncomeRecord(order models.Orders) error {
	if order.OrderStatus != 5 { // 已完成
		return nil
	}

	// 检查财务对账记录
	var financialRecord models.FinancialReconciliation
	err := config.DB.Where("order_id = ?", order.Id).First(&financialRecord).Error
	if err != nil {
		return fmt.Errorf("财务对账记录不存在: %v", err)
	}

	// 验证金额一致性
	expectedAmount := float64(order.Price * 100)
	if financialRecord.Amount != expectedAmount {
		return fmt.Errorf("金额不一致，订单金额: %d分，财务记录: %d分", expectedAmount, financialRecord.Amount)
	}

	// 验证交易类型
	if financialRecord.TransactionType != 1 {
		return fmt.Errorf("交易类型不正确，应为收入(1)，实际: %d", financialRecord.TransactionType)
	}

	return nil
}

// validateExpenseRecord 验证支出记录
func (s *Server) validateExpenseRecord(order models.Orders) error {
	if order.OrderStatus != 5 || order.UserId == 0 {
		return nil
	}

	// 检查账单记录
	var count int64
	err := config.DB.Model(&models.Billing{}).Where("user_id = ? AND user_type = 1", order.UserId).Count(&count).Error
	if err != nil {
		return fmt.Errorf("查询账单记录失败: %v", err)
	}

	if count == 0 {
		return fmt.Errorf("用户 %d 缺少账单记录", order.UserId)
	}

	return nil
}

// validatePaymentProcessing 验证支付处理
func (s *Server) validatePaymentProcessing(order models.Orders) error {
	if order.OrderStatus != 5 {
		return nil
	}

	// 验证支付方式
	validPayWays := map[int8]string{
		1: "支付宝",
		2: "微信支付",
		3: "信用卡",
		4: "电子钱包",
		5: "其他",
	}

	if _, exists := validPayWays[order.PayWay]; !exists {
		return fmt.Errorf("无效的支付方式: %d", order.PayWay)
	}

	// 验证支付时间
	if order.PayTime.IsZero() {
		return fmt.Errorf("支付时间未记录")
	}

	// 验证支付金额
	if order.Price <= 0 {
		return fmt.Errorf("支付金额无效: %.2f", order.Price)
	}

	return nil
}

// validateRefundProcessing 验证退款处理
func (s *Server) validateRefundProcessing(order models.Orders) error {
	// 检查退款时间
	if order.CancelTime.IsZero() {
		return fmt.Errorf("退款时间未记录")
	}

	// 检查退款财务记录
	var financialRecord models.FinancialReconciliation
	err := config.DB.Where("order_id = ? AND transaction_type = 2", order.Id).First(&financialRecord).Error
	if err != nil {
		return fmt.Errorf("退款财务记录不存在: %v", err)
	}

	// 验证退款金额
	expectedRefundAmount := float64(order.Price * 100)
	if financialRecord.Amount != expectedRefundAmount {
		return fmt.Errorf("退款金额不一致，期望: %d分，实际: %d分", expectedRefundAmount, financialRecord.Amount)
	}

	return nil
}

// validateCalculationLogic 验证计算逻辑
func (s *Server) validateCalculationLogic(order models.Orders) error {
	// 获取费用明细
	var pricingInfo models.PricingInformation
	err := config.DB.Where("order_id = ?", order.Id).First(&pricingInfo).Error
	if err != nil {
		return fmt.Errorf("费用明细不存在: %v", err)
	}

	// 验证起步价计算
	expectedStartingPrice := 20.0
	if order.CarTypeId == 2 {
		expectedStartingPrice = 30.0
	} else if order.CarTypeId == 3 {
		expectedStartingPrice = 10.0
	}

	if pricingInfo.PricesStarting != expectedStartingPrice {
		return fmt.Errorf("起步价计算错误，期望: %.2f，实际: %.2f", expectedStartingPrice, pricingInfo.PricesStarting)
	}

	// 验证里程费计算
	expectedMileageFee := 0.0
	if order.Distance > 10 {
		expectedMileageFee = (order.Distance - 10) * 3
	}

	if pricingInfo.MileageFee != expectedMileageFee {
		return fmt.Errorf("里程费计算错误，期望: %.2f，实际: %.2f", expectedMileageFee, pricingInfo.MileageFee)
	}

	// 验证总价计算
	expectedTotalPrice := pricingInfo.PricesStarting + pricingInfo.MileageFee + pricingInfo.DurationFee +
		pricingInfo.LongDistance + pricingInfo.Bridge + pricingInfo.NightServiceFee +
		pricingInfo.ParkingFee + pricingInfo.Other

	if pricingInfo.TotalPrice != expectedTotalPrice {
		return fmt.Errorf("总价计算错误，期望: %.2f，实际: %.2f", expectedTotalPrice, pricingInfo.TotalPrice)
	}

	return nil
}

// validateDataConsistency 验证数据一致性
func (s *Server) validateDataConsistency(order models.Orders) error {
	// 检查财务对账记录
	var financialRecord models.FinancialReconciliation
	err := config.DB.Where("order_id = ?", order.Id).First(&financialRecord).Error
	if err != nil {
		return fmt.Errorf("财务对账记录不存在: %v", err)
	}

	// 验证订单编号一致性
	if order.OrderSn != financialRecord.OrderSn {
		return fmt.Errorf("订单编号不一致，订单表: %s，财务表: %s", order.OrderSn, financialRecord.OrderSn)
	}

	// 验证金额一致性
	expectedAmount := float64(order.Price * 100)
	if financialRecord.Amount != expectedAmount {
		return fmt.Errorf("金额不一致，订单表: %d分，财务表: %d分", expectedAmount, financialRecord.Amount)
	}

	// 验证支付方式一致性
	if order.PayWay != int8(financialRecord.PayWay) {
		return fmt.Errorf("支付方式不一致，订单表: %d，财务表: %d", order.PayWay, financialRecord.PayWay)
	}

	return nil
}

// generateValidationSummary 生成验证汇总
func (s *Server) generateValidationSummary(resp *__.ComprehensiveValidationResp) *__.ValidationSummary {
	summary := &__.ValidationSummary{
		IncomeRecordsValid:     true,
		ExpenseRecordsValid:    true,
		PaymentProcessingValid: true,
		RefundProcessingValid:  true,
		FinancialReportsValid:  true,
		CalculationLogicValid:  true,
		DataConsistencyValid:   true,
		ConcurrencyValid:       true,
		OverallSuccess:         true,
	}

	// 根据错误和警告数量判断各项验证结果
	errorCount := 0
	warningCount := 0

	for _, detail := range resp.Details {
		errorCount += len(detail.Errors)
		warningCount += len(detail.Warnings)
	}

	// 如果有错误，则整体验证失败
	if errorCount > 0 {
		summary.OverallSuccess = false
	}

	// 根据错误类型判断各项验证结果
	for _, detail := range resp.Details {
		for _, err := range detail.Errors {
			if contains(err, "收入记录") {
				summary.IncomeRecordsValid = false
			}
			if contains(err, "支出记录") {
				summary.ExpenseRecordsValid = false
			}
			if contains(err, "支付处理") {
				summary.PaymentProcessingValid = false
			}
			if contains(err, "退款处理") {
				summary.RefundProcessingValid = false
			}
			if contains(err, "计算逻辑") {
				summary.CalculationLogicValid = false
			}
			if contains(err, "数据一致性") {
				summary.DataConsistencyValid = false
			}
		}
	}

	return summary
}

// contains 检查字符串是否包含子字符串
func contains(s, substr string) bool {
	return len(s) >= len(substr) && s[:len(substr)] == substr
}
